﻿using gt.webapi.core.Entity.Options;
using gt.webapi.core.Filters;
using gt.webapi.core.Handlers;
using System;
using System.Web.Http;
using System.Web.Http.ExceptionHandling;

namespace gt.webapi.core
{
    public static class HttpConfigurationExtension
    {
        public static void RegisterWebApiCore(this HttpConfiguration config, WebApiCoreOption option)
        {
            if (option == null) throw new ArgumentNullException("option");

            config.MessageHandlers.Insert(0, new AppkeyHandler());

            if (option.Log != null)
            {
                config.MessageHandlers.Insert(1, new LogHandler(option.Log.Logger));
                config.Filters.Add(new ActionExceptionFilterAttribute(option.Log.Logger));
                config.Services.Replace((typeof(IExceptionHandler)), new ErrorHandler(option.Log.Logger));
            }

            if (option.IpLimit != null)
                config.MessageHandlers.Add(new IpLimitHandler(option.IpLimit.Repository));

            if (option.RateLimit != null)
                config.Filters.Add(new RateLimitFilterAttribute(option.RateLimit.Repository));

            if (option.Authority != null && option.Authority.AuthenticationFilter != null)
            {
                config.Filters.Add(option.Authority.AuthenticationFilter);
                config.Filters.Add(option.Authority.AuthorizeFilter);
            }
        }
    }
}
